package com.example.longpolling;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author denis.huang
 * @since 2018/10/19 17:04
 */
@Service
public class MsgService {
  private Map<String, List<DeferredResult<String>>> deferredResultMap = new HashMap<>();

  public void add(String key, DeferredResult<String> deferredResult) {
    List<DeferredResult<String>> deferredResults = deferredResultMap.get(key);
    if (deferredResults == null) {
      deferredResults = new ArrayList<>();
    }
    deferredResults.add(deferredResult);
    deferredResultMap.put(key, deferredResults);
  }

  public void send(String key, String msg) {
    List<DeferredResult<String>> deferredResults = deferredResultMap.get(key);
    if (!CollectionUtils.isEmpty(deferredResults)) {
      deferredResults.forEach(dr -> {
        if (dr != null && !dr.hasResult()) {
          dr.setResult(msg);
        }
      });
    }
  }

  public void remove(String key) {
    deferredResultMap.remove(key);
  }
}
